layui.use(['jquery', 'gateway','backend'], function() {
    var gateway = layui.gateway,
        backend = layui.backend;

    var allTimeSeries = {};
    var allValueLabels = {};
    var descriptions = {
        'Processes': {
            'r': '等待运行时间的进程数',
            'b': '正在睡眠的进程数'
        },
        'Memory': {
            'swpd': '虚拟内存',
            'free': '空闲内存',
            'buff': '缓冲内存用量',
            'cache': '缓存内存用量'
        },
        'Swap': {
            'si': '磁盘交换量',
            'so': '内存交换量'
        },
        'IO': {
            'bi': '接收量',
            'bo': '发送量'
        },
        'System': {
            'in': '每秒中断数，包括时钟',
            'cs': '每秒上下文切换数'
        },
        'CPU': {
            'us': '运行非内核代码所花费的时间（用户时间，包括空闲时间）',
            'sy': '运行内核代码所花费的时间（系统时间）',
            'id': '空闲时间',
            'wa': '等待IO所花费的时间'
        }
    };

    var streamStats = function () {
        var colHeadings = 'r  b   swpd   free   buff  cache   si   so    bi    bo   in   cs us sy id wa\n'.trim().split(/ +/);;
        gateway.init();

        gateway.on('afterBindwk', function (client_id) {
            backend.api.ajax({
                url : '/admin/index/joingroup',
                data : {group: 'vmstat', client_id : client_id}
            }, function() {
                return false;
            });
        });


        gateway.on('vmstat', function (data) {
            var colValues = data.trim().split(/ +/);
            var stats = {};
            for (var i = 0; i < colHeadings.length; i++) {
                stats[colHeadings[i]] = parseInt(colValues[i]);
            }
            receiveStats(stats);
        });
    };

    var initCharts = function () {
        Object.each(descriptions, function(sectionName, values) {
            var section = $('.chart.template').clone().removeClass('template').appendTo('#charts');

            section.find('.title').text(sectionName);

            var smoothie = new SmoothieChart({
                grid: {
                    sharpLines: true,
                    verticalSections: 5,
                    strokeStyle: 'rgba(119,119,119,0.45)',
                    millisPerLine: 1000
                },
                minValue: 0,
                labels: {
                    disabled: true
                }
            });
            smoothie.streamTo(section.find('canvas').get(0), 1000);

            var colors = chroma.brewer['Pastel2'];
            var index = 0;
            Object.each(values, function(name, valueDescription) {
                var color = colors[index++];

                var timeSeries = new TimeSeries();
                smoothie.addTimeSeries(timeSeries, {
                    strokeStyle: color,
                    fillStyle: chroma(color).darken().alpha(0.5).css(),
                    lineWidth: 3
                });
                allTimeSeries[name] = timeSeries;

                var statLine = section.find('.stat.template').clone().removeClass('template').appendTo(section.find('.stats'));
                statLine.attr('title', valueDescription).css('color', color);
                statLine.find('.stat-name').text(name);
                allValueLabels[name] = statLine.find('.stat-value');
            });
        });
    };

    var receiveStats = function (stats) {
        Object.each(stats, function(name, value) {
            var timeSeries = allTimeSeries[name];
            if (timeSeries) {
                timeSeries.append(Date.now(), value);
                allValueLabels[name].text(value);
            }
        });
    };

    initCharts();
    streamStats();
});
